import enums from '@/utils/enum'

/**
 * 页面表单组合式函数
 * 
 * @param {Object} formRef 表单 ref，必填
 * @param {String} moduleName 模块名称，必填
 * @param {Object} defaultFormData 默认表单数据
 * @param {Function} beforeOpenFn 打开页面之前回调
 * @param {Function} addApi 新增保存接口
 * @param {Function} updateApi 修改保存接口
 */
export const useFormPage = (
  formRef,
  moduleName = '',
  defaultFormData = {},
  beforeOpenFn,
  addApi,
  updateApi
) => {
  const state = reactive({
    form: {},
    loading: false
  })
  
  const { formType } = enums
  
  const { proxy } = getCurrentInstance()
  
  const router = useRouter()
  
  const close = () => {
    proxy.$tab.closePage(router.currentRoute.value)
    router.back()
  }
  
  /**
   * 表单重置
   */
  const resetForm = () => {
    state.form = JSON.parse(JSON.stringify(defaultFormData))
    formRef?.value?.resetFields()
  }
  
  /**
   * 打开页面
   */
  const open = async () => {
    resetForm()
    if (beforeOpenFn) {
      proxy.$modal.loading('加载中...')
      await beforeOpenFn().catch(err => {
        console.error(err)
        close()
      })
      .finally(() => {
        proxy.$modal.closeLoading()
      })
    }
  }
  
  /**
   * 表单提交
   * 
   * @param {Function} submitOkFn 提交成功回调
   */
  const submitForm = async (submitOkFn) => {
    formRef.value.validate(valid => {
      if (valid) {
        const type = state.form.id != null ? 'edit' : 'add'
        const api = type === 'edit' ? updateApi : addApi
        state.loading = true
        api(state.form).then(res => {
          if (!res.msg) proxy.$modal.msgSuccess(`${formType[type].title}${moduleName}成功`)
          submitOkFn?.(res, type)
          close()
        }).finally(() => {
          state.loading = false
        })
      } else {
        proxy.$modal.msgWarning('数据校验不通过，请核实!')
      }
    })
  }
  
  /**
   * 表单提交，用于非新增/编辑
   * 
   * @param {Function} saveApi 保存接口
   * @param {String} successTxt 操作成功提示信息
   * @param {Function} submitOkFn 提交成功回调
   * @param {Boolean} okClose 提交成功后是否关闭页面
   */
  const submitPage = async (saveApi, successTxt, submitOkFn, okClose = true) => {
    formRef.value.validate(valid => {
      if (valid) {
        state.loading = true
        saveApi(state.form).then(res => {
          if (!res.msg) proxy.$modal.msgSuccess(successTxt)
          submitOkFn?.(res)
          okClose && close()
        }).finally(() => {
          state.loading = false
        })
      } else {
        proxy.$modal.msgWarning('数据校验不通过，请核实!')
      }
    })
  }

  return {
    ...toRefs(state),
    open,
    close,
    submitForm,
    submitPage
  }
}